from sqlalchemy.orm import Session
from sqlalchemy import select
from models import Student as StudentORM
from models import Option
from models import CheckIsRight as CIR
from schemas import StudentCreate

def create_student(db: Session, stu: StudentCreate):
    db_obj = StudentORM(**stu.dict())
    db.add(db_obj)
    db.commit()
    db.refresh(db_obj)
    return db_obj

def get_all_students(db: Session):
    return db.query(StudentORM).all()


def get_option_value(db: Session, opkey: str) -> str | None:
    """返回当前 opvalue，不存在返回 None"""
    obj = db.scalar(select(Option).where(Option.opkey == opkey))
    return obj.opvalue if obj else None

def incr_option_value(db: Session, opkey: str) -> str:
    """原子 +1（先转 int，再 str 存回）"""
    obj = db.scalar(select(Option).where(Option.opkey == opkey))
    if obj is None:
        # 不存在则创建，初始 "1"
        obj = Option(opkey=opkey, opvalue="1")
        db.add(obj)
    else:
        obj.opvalue = str(int(obj.opvalue or 0) + 1)
    db.commit()
    db.refresh(obj)
    return obj.opvalue

def zero_option_value(db: Session, opkey: str) -> str:
    """重置为 "0" """
    obj = db.scalar(select(Option).where(Option.opkey == opkey))
    if obj is None:
        obj = Option(opkey=opkey, opvalue="0")
        db.add(obj)
    else:
        obj.opvalue = "0"
    db.commit()
    db.refresh(obj)
    return obj.opvalue

def get_all_check(db: Session) -> list[CIR]:
    return db.scalars(select(CIR)).all()

def update_isright(db: Session, stuid: int, is_right: int) -> None:
    # 存在就更新，不存在就插入
    obj = db.scalar(select(CIR).where(CIR.stuid == stuid))
    if obj:
        obj.isright = bool(is_right)
    else:
        obj = CIR(stuid=stuid, isright=bool(is_right))
        db.add(obj)
    db.commit()